package com.example.service.impl;

import com.example.dao.RoleDao;
import com.example.dao.UserDao;
import com.example.domain.Role;
import com.example.domain.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;

    public List<User> list() {
        List<User> userList=userDao.getAll();
        for (User user : userList) {
            List<Role> roles=roleDao.getRolesByUserId(user.getId());
            user.setRoles(roles);
        }
        return userList;
    }

    public void save(User user, Long[] roleIds) {
        Long userId=userDao.save(user);
        userDao.saveUserRoleRel(userId,roleIds);
    }

    public void del(Long userId) {
        //删除用户与角色的关系
        userDao.delUserRoleRel(userId);
        //删除用户
        userDao.del(userId);
    }

    public User login(String username, String password) {
        try {
            User user = userDao.login(username,password);
            return user;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return null;
        }

    }
}
